package zunge.twitterdel.foursquare;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Node;

public class TreeHierarchy<T> {
	Node rootNode;
	HashMap<T, Node> index;
	
	public TreeHierarchy(T root){
		index = new HashMap<T,Node>();
		this.rootNode = new Node(root);
		index.put(root,rootNode);
	}
	
	public void addRelation(T src, T tgt){
		System.err.println("add "+src+"\t"+tgt);
		
		if(!index.containsKey(src)){
			Node nsrc = new Node(src);
			nsrc.parent = rootNode;
			rootNode.children.add(nsrc);
			index.put(src, nsrc);
		}
		if(!index.containsKey(tgt)){index.put(tgt, new Node(tgt));}
		Node nsrc = index.get(src);
		Node ntgt = index.get(tgt);
		
		nsrc.children.add(ntgt);
	
		ntgt.parent = nsrc;
	}
	
	class Node{
		public T data;
		public Node parent;
		public List<Node> children;
		public Node(T data){
			this.data =data;
			parent = null;
			children = new ArrayList<Node>();
		}
	}
	
	public void printHierarchy(){
		printItem(rootNode, 0);
	}
	void printItem(Node n, int index){
		if(index>0){ for(int i = 0;i < index;++i){System.out.print("\t");} }
		System.out.print(n.data.toString()+"\n");
		for(Node sn:n.children){
			printItem(sn, index+1);
		}
	}
	
	public T getSubRoot(T item){
		if(!index.containsKey(item)){return null;}
		Node n = index.get(item);
		while(!n.parent.equals(rootNode)){
			n = n.parent;
		}
		return n.data;
	}
}
